<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author: zl
// +----------------------------------------------------------------------

namespace app\crm\controller;

use app\admin\controller\ApiCommon;

use app\crm\model\BalanceLog;
use app\crm\model\Setting;
use app\crm\model\SettingCategory;
use app\crm\model\Service;
use app\crm\model\ReturnVist;
use app\crm\model\Customer as CustomerModel;
use app\crm\model\TransferShop;
use app\shop\model\Order;
use \app\crm\model\ProductItem;
use \app\crm\model\ShopGoods;
use think\response\Json;
use think\facade\Db;


class Goods extends ApiCommon
{
    protected $customerModel;
    protected $customerConfigModel;

    /**
     * 用于判断权限
     * @permission 无限制
     * @allow 登录用户可访问
     * @other 其他根据系统设置
     **/

    public function initialize()
    {
        $action = [
            'permission' => ['house_list','setcustomerage','setzycustomer','dsmonth','setmonth'],
            'allow' => ['users', 'info']
        ];
        event('CheckAuth',$action);
        $request = $this->request;
        $a = strtolower($request->action());

        $this->customerModel = new CustomerModel();
        if (!in_array($a, $action['permission'])) {
            parent::initialize();
        }
    }

    //获取商品列表-出库单和退库单使用
    public function getList(): Json
    {

        try {
//            $shopIds = $this->getCommonShopIdsCollectByUserType();
//            $this->param['shopIds'] = $shopIds;
//            $this->param['user_id'] = $this->userInfo['id'];
//            $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

            $param = $this->param;
            if(!isset($param['type'])){
                throw new \Exception('商品类型不存在');
            }
            if(!in_array($param['type'],[1,2])){
                throw new \Exception('商品类型不合法');
            }
            if($param['type'] == 1){
                //品项
                $productItemModel  = new ProductItem();
                $goods = $productItemModel->getGoodsList();
            }else{
                //商品
               $shopGoodsModel = new ShopGoods();
               $goods = $shopGoodsModel->getGoodsList();
            }
            return resultArray(['data' => $goods]);
        }catch (\Exception $e){
            return resultArray(['error' => $e->getMessage()]);
        }
    }



    /**
     * 获取当前登录用户可以读取的店铺列表
     * 未完成
     */
    public function getCustomerShopList(CustomerModel $customerModel): Json
    {
        $param = $this->param;
        $type  = isset($param['type']) ? intval($param['type']) : 0;

        /*调用读取shop_id集合的方法*/
        $where = array();
        if ($param['type'] == 0){
            $data           = Db::name('shop')->where($where)->column('shop_id,shop_name');
        }else{
            $data['out']    = Db::name('shop')->where($where)->column('shop_id,shop_name');
            $data['enter']  = Db::name('shop')->where($where)->column('shop_id,shop_name');
        }

        return resultArray(['data' => $data]);
    }

    /**
     * 列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function list(CustomerModel $customerModel): Json
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function list_export(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['export']  = 1;
        $type = $this->param['type'] ?? 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }

        if ($type == 1 || $type == 2 ){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '姓名',
                'telephone'      => '联系电话',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'source_name'      => '来源',
                'effective_entry'      => '是否进店',
                'grade_name'      => '会员等级',
                'nurse_name'      => '护理师',
                'customer_service_name'      => '客服',
                'shop_name'      => '门店/门诊',
                'turn_status'      => '转店状态',
                'progress_name'      => '修复进展',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 3){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '姓名',
                'sex'      => '性别',
                'age'      => '年龄',
                'source_name'      => '来源',
                'new_join_shop_time'      => '进店时间',
                'grade_name'      => '会员等级',
                'nurse_name'      => '负责人',
                'shop_name'      => '门店/门诊',
                'customer_service_name'      => '客服',
                'turn_status'      => '转店状态',
                'progress_name'      => '修复进展',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 4){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '顾客姓名',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'new_join_shop_time'      => '进店时间',
                'nurse_name'      => '护理师',
                'shop_name'      => '门店/门诊',
                'grade_name'      => '会员等级',
                'class_name'      => '客户分类',
                ''      => '消费时间',
                ''      => '服务时间',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 5){
            $callName = [
                'create_time'      => '录入时间',
                'customer_name'      => '顾客姓名',
                'telephone'      => '手机号姓名',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'new_join_shop_time'      => '进店时间',
                'nurse_name'      => '护理师',
                'shop_name'      => '门店/门诊',
                'grade_name'      => '会员等级',
                'class_name'      => '客户分类',
                ''      => '消费时间',
                ''      => '服务时间',

                'last_kftime'      => '回访时间',
                'scar_aggregate'      => '疤痕类型',
                'consumption'      => '消费金额',
            ];
        }else if ($type == 6){
            $callName = [
                'cj_time'      => '成交时间',
                'customer_name'      => '顾客姓名',
                'telephone'      => '手机号',
                'sex'      => '性别',
                'age'      => '年龄',
                'birthday'      => '生日',
                'source_name'      => '来源',
                'grade_name'      => '会员等级',
                'market_name'      => '市场',
                'shop_name'      => '店面',
                'nurse_name'      => '护理师',
                'cj_money'      => '成交金额',
                'progress_name'      => '修复进展',
                'scar_aggregate'      => '疤痕类型',
            ];

        }

        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新单列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function newOrderlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id']    = $this->userInfo['id'];
        $this->param['shopIds']    = $shopIds;
        $this->param['isNewOrder']    = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 回访列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function clientVisitlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id']    = $this->userInfo['id'];
        $this->param['shopIds']    = $shopIds;

        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 流失列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function drainlist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['isDrain'] = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 预警列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function warninglist(CustomerModel $customerModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        $this->param['isWarning'] = 1;
        $data = $customerModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 审核列表
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function auditList(Service $serviceModel): Json
    {
        // $data = [
        //     'list' => '审核列表'
        // ];
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        // $this->param['isWarning'] = 1;
        $data = $serviceModel->auditList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 提交审核
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function submitAudit(Service $serviceModel)
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['shopIds'] = $shopIds;
        // $this->param['isWarning'] = 1;
        $data = $serviceModel->submitAudit($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 商机详情
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function read(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['user_phone'] = $this->userInfo['mobile'];

        $data = $customerModel->getDataInfo($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 获取客户门诊id
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function readCustomerId(CustomerModel $customerModel): Json
    {
        $request = $this->param;

        $telephone = Db::name('customer')->where('id',$request['id'])->value('telephone');

        $ids = Db::name('customer')->alias('c')
            ->join('shop s', 's.shop_id = c.shop_id', 'LEFT')
            ->where('c.telephone',$telephone)->column('c.id','s.shop_type');


        return resultArray(['data' => $ids]);
    }

    /**
     * 添加
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function create(CustomerModel $customerModel): Json
    {
        $this->param['operator'] = $this->userInfo['id'];
        $data = $customerModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => $customerModel->getError(), 'data'=>[]]);
    }

    /**
     * 编辑
     * @param  CustomerModel $customerModel
     * @return Json
     */
    public function update(CustomerModel $customerModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $customerModel->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => $customerModel->getError(), 'data'=>[]]);
    }

    /**
     * 基础设置列表
     * @param  SettingCategory $settingCategory
     * @return Json
     */
    public function settingCategory(SettingCategory $settingCategory): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingCategory->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingCategory->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  SettingCategory $settingCategory
     * @return Json
     */
    public function settingInfo(Setting $setting): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $setting->settingInfo($this->param);
        if (!$data) {
            return resultArray(['error' => $setting->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  Setting $settingModel
     * @return Json
     */
    public function settingList(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->getAllDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 基础设置列表
     * @param  Setting $settingModel
     * @return Json
     */
    public function setting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 添加
     * @param  Setting $settingModel
     * @return Json
     */
    public function createSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 编辑
     * @param  Setting $settingModel
     * @return Json
     */
    public function updateSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->saveData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 删除
     * @param  Setting $settingModel
     * @return Json
     */
    public function deleteSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->deleteData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 状态
     * @param  Setting $settingModel
     * @return Json
     */
    public function statusSetting(Setting $settingModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $settingModel->statusData($this->param);
        if (!$data) {
            return resultArray(['error' => $settingModel->getError()]);
        }
        return resultArray(['error' => $settingModel->getError(), 'data'=>[]]);
    }

    /**
     * 转店列表
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShopList(TransferShop $transferShop): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $transferShop->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 转店列表 导出
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShopList_export(TransferShop $transferShop): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export']  = 1;
        $data = $transferShop->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        $callName = [
            'out_shop_name' => '转出门店/门诊',
            'create_time' =>'转出时间',
            'customer_name' =>'客户名称',
            'operator_name' => '操作员工',
            'in_shop_name' => '转入门店/门诊',
            'reason' => '转店原因'
        ];
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 手机号验证
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function verifyPhone(TransferShop $transferShop): Json
    {

        $data = $transferShop->verifyPhone($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['data' => $data]);
    }


    /**
     * 添加转店
     * @param  TransferShop $transferShop
     * @return Json
     */
    public function transferShop(TransferShop $transferShop): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $transferShop->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $transferShop->getError()]);
        }
        return resultArray(['error' => $transferShop->getError(), 'data'=>[]]);
    }

    /**
     * 服务列表
     * @param  Service $serviceModel
     * @return Json
     */
    public function serviceList(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['user_shop_id'] = $this->userInfo['shop_id'];

        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $serviceModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }

        // 导出
        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            $callName = [

                'create_time'   =>'开卡日期',

                'customer_name' =>'顾客姓名',
                'telephone' =>'手机号',

                'source_name' =>'来源',

                'last_shop_time'=>'最新到店日期',

                'kk_user_name' =>'开卡人',

                'shop_name' =>'开卡部门',

                'name' =>'开卡名称',
                'goods_alias_name' =>'开卡别名',

                'kk_money'     =>'开卡金额',
                'consume_money'=>'消耗本金',
                'consume_gratuity'=>'消耗赠金',
                'consume_store_transfer'=>'消耗店转',

                'num'   =>'开卡次数',

                'yy_num'    =>'剩余次数',

                'start_time'    =>'开始时间',

                'end_time'      =>'结束时间',

                'sy_num'    =>'消耗次数',
                'remark'  =>'备注'
            ];


            if($data['list']){


                $downUrl = exportExcelData('服务列表导出',$callName,$data['list'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }

        return resultArray(['data' => $data]);
    }

    /**

     * 核销列表

     * @param  Service $serviceModel

     * @return Json

     */
    public function serveContent(Service $serviceModel): Json
    {

        $shopIds = $this->getCommonShopIdsCollectByUserType();

        $this->param['shopIds'] = $shopIds;

        $this->param['user_id'] = $this->userInfo['id'];

        $this->param['shop_person_id'] = $this->userInfo['shop_person_id'];

        $data = $serviceModel->getDataLog($this->param);

        if (!$data) {

            return resultArray(['error' => $serviceModel->getError().'23232']);

        }
        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            if(date('Y-m',strtotime($this->param['start_time'])) != date('Y-m',strtotime($this->param['endTime'])))
                return resultArray(['error' => "只能导出一个月内的数据"]);

            $callName = [

                'create_time'   =>'服务日期',

                'kk_time' =>'开卡日期',

                'customer_name' =>'客户姓名',

                'sex' =>'性别',

                'age' =>'年龄',

                'shop_name' =>'门店',

                'market_name'     =>'市场',

                'nurse_name'   =>'负责人',

                'name'    =>'卡项名称',

                'consume_money'=>'消耗本金',
                'consume_gratuity'=>'消耗赠金',
                'consume_store_transfer'=>'消耗店转',

                'nurse_id_one_name'    =>'护理师1',

                'nurse_id_two_name'      =>'护理师2',

                'experience'    =>'服务类型',

                'fw_num'    =>'服务次数',

                'station_name'    =>'核销店长',

                'pt'    =>'核销平台',

                'mark'  =>'备注'

            ];


            if($data['service_log']){
                $downUrl = exportExcelData('核销列表导出',$callName,$data['service_log'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }
        return resultArray(['data' => $data]);


    }

    /**

     * 护理统计

     * @param  Service $serviceModel

     * @return Json

     */
    public function serviceNursing(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();

        $this->param['shopIds'] = $shopIds;

        $this->param['user_id'] = $this->userInfo['id'];

        $data = $serviceModel->getDataNursing($this->param);
//        $totalData = $serviceModel->getTotalData($this->param);
        // echo "<pre>";
        // print_r($data['service_log']);
        // exit;
        //print_r($data);
        if (!$data) {

            return resultArray(['error' => $serviceModel->getError()]);

        }
//        array_push($data['service_log'],$totalData);

        $is_export = $this->param['export'] ?? 0;

        if($is_export == 1){

            $callName = [

                'market_name'   =>'市场',

                'shop_name' =>'门店',

                'name' =>'员工姓名',

                'station_name' =>'等级',

                'bahennum' =>'疤痘护理',

                'mianbunum'     =>'面部护理',

                'shentinum'   =>'项目身体护理',

                'shengming'    =>'生命之源',

                'jingluotong'    =>'经络通',

                'shuganliqi'      =>'疏肝理气',

                'jichubushui'    =>'基础补水',

                'total'    =>'护理总数',

            ];


            if($data['service_log']){


                $downUrl = exportExcelData('护理统计明细',$callName,$data['service_log'],'xlsx',1);

                return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

                exit;

            }else{

                return resultArray(['error' => '请选择导出门店！！！']);

            }


        }


        return resultArray(['data' => $data]);


    }

    /**
     * 服务详情
     * @param  Service $serviceModel
     * @return Json
     */
    public function readService(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->getDataInfo($this->param);
        if (!$data) {
            return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,$serviceModel->getError()]);
    }

    /**
     * 服务详情
     * @param  Service $serviceModel
     * @return Json
     */
    public function addServiceLog(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->addServiceLog($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
    }


    /**
     * 调整服务卡项
     * @param  Service $serviceModel
     * @return Json
     */
    public function changeService(Service $serviceModel)
    {
        $this->param['user_id'] = $this->userInfo['id'];
        // echo "<pre>";
        // print_r($this->param);
        $data = $serviceModel->changeService($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data,'error' => $serviceModel->getError()]);
    }


    /**
     * 余额变动记录
     * @param  BalanceLog $balanceLog
     * @return Json
     */
    public function createBalanceLog(BalanceLog $balanceLog): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $balanceLog->addData($this->param);
        if (!$data) {

            return resultArray(['error' => $balanceLog->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 每年重新搞一下名字
     */
    public function setCustomerAge(CustomerModel $customerModel):Json
    {
        $data = $customerModel->setCustomerAge($this->param);
        if (!$data) {

            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['data' => []]);
    }

    /**
     * 更新进店时间
     * 更新转店状态
     */
    public function setCustomerStatus(CustomerModel $customerModel):Json
    {
        $param  = $this->param;
        $data = $customerModel->setCustomerStatus($this->param);
        if (!$data) {
            return resultArray(['error' => $customerModel->getError()]);
        }
        return resultArray(['error' => '更新成功','data' => []]);
    }

    /**
     * 会员等级列表
     */
    public function getGradeList(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param  = $this->param;
        $data   = $CustomerGradeModel->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 添加会员等级的基础数据获取
     */
    public function addGradeDetail(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->addGradeDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 添加会员等级
     */
    public function addGrade(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->addGrade($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '添加成功','data' => $data]);
    }

    /**
     * 编辑会员等级
     */
    public function saveGrade(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->saveGrade($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '编辑成功','data' => $data]);
    }

    /**
     * 获取详情
     */
    public function gradeDetail(CustomerGradeModel $CustomerGradeModel): Json
    {
        $param = $this->param;
        $data   = $CustomerGradeModel->gradeDetail($this->param);
        if (!$data) {
            return resultArray(['error' => $CustomerGradeModel->getError()]);
        }
        return resultArray(['error' => '','data' => $data]);
    }

    /**
     * 某个客户的优惠券
     */
    public function getCouponProvide(): Json
    {
        $param      = $this->param;
        $shop_id    = $param['shop_id'] ?? 0;
        $customer_id= $param['customer_id'] ?? 0;
        $type= $param['type'] ?? 0;

        if ($shop_id == 0 && $customer_id == 0 ) {
            return resultArray(['error' => '数据类型错误']);
        }

        $where = array();
        if ($shop_id) {

        } else {
            array_push($where,['customer_id','=',$customer_id]);

            $c_where = [];

            array_push($c_where,['start_time','<',time()]);
            array_push($c_where,['end_time','>',time()]);
            $shop_goods = Db::name('coupon')->where($c_where)->column('id');

            array_push($where,['coupon_id','in',$shop_goods]);
        }
        $list       = Db::name('coupon_provide_customer')->where($where)->select()->toArray();
        $yhjIds     = array_column($list,'coupon_id');
        if ($yhjIds) {
            $files = [
                'id',
                'name',
                'use_type',
                'type',
                'use_threshold',
                'denomination',
                'start_time',
                'end_time',
                'status',
            ];
            $where = [];
            array_push($where,['id','in',$yhjIds]);
            if($type == 1){
                array_push($where,['type','=',$type]);
            }else if($type == 2){
                array_push($where,['type','=',$type]);
            }else if($type == 3){
                array_push($where,['type','=',$type]);
            }
            $yhjlist   = Db::name('coupon')->where($where)->column($files,'id');
            // print_r($yhjlist);exit;
        }
        foreach ($list as $key => $val){
            if ($yhjlist[$val['coupon_id']]['end_time'] >= time() && $yhjlist[$val['coupon_id']]['start_time'] <= time() && $yhjlist[$val['coupon_id']]['status'] != 1 ) {
                $list[$key]['status']    = 2;
            }
            if ($yhjlist[$val['coupon_id']]['start_time'] > time()) {
                $list[$key]['status']    = 3;
            }
            // print_r($val);
            // print_r($yhjlist);
            // $list[$key]['id']            = $yhjlist[$val['id']]['id'] ? $yhjlist[$val['id']]['id'] : 0;
            $list[$key]['name']          = $yhjlist[$val['coupon_id']]['name'] ? $yhjlist[$val['coupon_id']]['name'] : '';
            $list[$key]['use_type']      = $yhjlist[$val['coupon_id']]['use_type'] ? $yhjlist[$val['coupon_id']]['use_type'] : 0;
            $list[$key]['use_threshold'] = $yhjlist[$val['coupon_id']]['use_threshold'] ? $yhjlist[$val['coupon_id']]['use_threshold'] : 0;
            $list[$key]['denomination']  = $yhjlist[$val['coupon_id']]['denomination'] ? $yhjlist[$val['coupon_id']]['denomination'] : 0;
            $list[$key]['start_time']    = $yhjlist[$val['coupon_id']]['start_time'] ? date('Y-m-d H:i:s',$yhjlist[$val['coupon_id']]['start_time']) : 0;
            $list[$key]['end_time']      = $yhjlist[$val['coupon_id']]['end_time'] ? date('Y-m-d H:i:s',$yhjlist[$val['coupon_id']]['end_time']) : 0;
            // $list[$key]['status']        = $yhjlist[$val['id']]['id'] ? $yhjlist[$val['id']]['id'] : 0;
            $list[$key]['create_time']      = $list[$key]['create_time'] ? date('Y-m-d H:i:s',$list[$key]['create_time']) : 0;
            $list[$key]['use_time']      = $list[$key]['use_time'] ? date('Y-m-d H:i:s',$list[$key]['use_time']) : '未使用';
            $list[$key]['endTimeT']      = $yhjlist[$val['coupon_id']]['end_time'] ? $yhjlist[$val['coupon_id']]['end_time'] : 0;
            $type = $yhjlist[$val['coupon_id']]['type'] ?? 0;
            if ($type == 1) {
                // code...
                $type_name = '满减券';
            }else if($type == 2){
                $type_name = '满赠券';
            }else {
                $type_name = '兑换券';
            }
            $list[$key]['type_name']      = $type_name;
            $list[$key]['type']      = $type;
        }

        /* $i = 0;
        foreach ($list as $k => $v){

            if($v['endTimeT'] >= time()){

                $list_t[$i]['id'] =$v['id'];
                $list_t[$i]['coupon_id'] =$v['coupon_id'];
                $list_t[$i]['customer_id'] =$v['customer_id'];
                $list_t[$i]['staus'] =$v['staus'];
                $list_t[$i]['create_time'] =$v['create_time'];
                $list_t[$i]['use_time'] =$v['use_time'];
                $list_t[$i]['order_id'] =$v['order_id'];
                $list_t[$i]['order_sn'] =$v['order_sn'];
                $list_t[$i]['user_id'] =$v['user_id'];
                $list_t[$i]['name'] =$v['name'];
                $list_t[$i]['use_type'] =$v['use_type'];
                $list_t[$i]['use_threshold'] =$v['use_threshold'];
                $list_t[$i]['denomination'] =$v['denomination'];
                $list_t[$i]['start_time'] =$v['start_time'];
                $list_t[$i]['end_time'] =$v['end_time'];
                $list_t[$i]['type_name'] =$v['type_name'];
                $list_t[$i]['type'] =$v['type'];

                $i ++;
            }else{
                $list_t[0]['dd']=1;
            }

        } */
        /* echo '<pre>';
        print_r($list_t);exit; */
        return resultArray(['error' => '','data' => $list]);
    }
    /**
     * 某个客户的优惠券兑换时的客户信息
     */
    public function getCouponProvideCustomer(): Json
    {
        $param      = $this->param;
        $yhj_id     = $param['yhj_id'] ?? 0;

        $where = [];
        array_push($where,['id','=',$yhj_id]);
        $fubiaoInfo     = Db::name('coupon_provide_customer')->where($where)->find();
        if (empty($fubiaoInfo)) {
            return resultArray(['error' => '优惠券不存在']);
        }
        $yhjInfo        = Db::name('coupon')->where('id','=',$fubiaoInfo['coupon_id'])->find();
        if (empty($yhjInfo)) {
            return resultArray(['error' => '优惠券不存在']);
        }
        $customerInfo   = Db::name('customer')->where('id','=',$fubiaoInfo['customer_id'])->find();
        if (empty($customerInfo)) {
            return resultArray(['error' => '客户不存在']);
        }
        $shopInfo   = Db::name('shop')->where('shop_id','=',$customerInfo['shop_id'])->find();
        if (empty($shopInfo)) {
            return resultArray(['error' => '店铺不存在']);
        }
        $personInfo   = Db::name('shop_person')->where('id','=',$customerInfo['nurse_id'])->find();
        if (empty($personInfo)) {
            return resultArray(['error' => '护理师不存在']);
        }
        $data = [];
        // 销售部门
        $data['sales_name']       = $shopInfo['shop_name']; //店名
        // 客户姓名
        $data['customer_name']    = $customerInfo['customer_name']; // 客户名称
        // 护理师（开单人）
        $data['sale_name']        = $personInfo['name']; // 护理师
        // 业务类型
        $data['business_type']    = $yhjInfo['use_type'] == 1 ? '疤痕' :'项目'; // 优惠券的类型
        // 订单类型
        $data['order_type']       = '补单'; // 默认补单
        // 销售组织
        $data['sales_organization']       = $shopInfo['market_name']; // 门店的归属市场
        // 发货组织
        $data['settlement_name']  = $shopInfo['market_name']; // 门店的归属市场
        // 发货部门
        $data['settlement_bumen_name']    = $shopInfo['market_name']; // 门店的归属市场
        // 发货仓库
        $data['settlement_cangku_name']  = $shopInfo['store_name'];  // 门店的归属市场
        // 成交日期
        $data['deal_time']        = date('Y-m-d'); // 当前时间
        $data['goodsList']        = []; // 可兑换的商品集合

        $goodsIds    = $yhjInfo['goods_id'];
        if ($goodsIds) {
            // code...
            $goodsList  = Db::name('shop_goods')->where('id','in',$goodsIds)->select()->toArray();
            foreach ($goodsList as $key => $val){
                $goodsList[$key]['pay_price'] = '0.00';
                $goodsList[$key]['number'] = '1';
            }
            $data['goodsList'] = $goodsList;
        }
        return resultArray(['error' => '获取成功','data' => $data]);
    }
    /**
     * 获取订单支付金额
     */
    public function getPayment(): Json
    {
        $param = $this->param;

        // 设置返回数据
        $balanceType = [
            1=>[
                'this' => 'zc_goods',
                'all'  => 'zc_allgoods'
            ],
            2=>[
                'this' => 'zc_fuwu',
                'all'  => 'zc_allfuwu'
            ],
            3=>[
                'this' => 'zc_fuwu',
                'all'  => 'zc_allfuwu'
            ],
            4=>[
                'this' => 'zc_fuwu',
                'all'  => 'zc_allfuwu'
            ],
        ];
        $retuenData = [
            'zc_goods_y'    => '0.00', // 疤痕需要支付的余额
            'zc_goods_z'    => '0.00', // 疤痕需要支付的赠金
            'zc_goods_d'    => '0.00', // 疤痕需要支付的店转
            'zc_allgoods_z' => '0.00', // 疤痕需要支付的总金额
            'zc_fuwu_y'     => '0.00', // 服务需要支付的余额
            'zc_fuwu_z'     => '0.00', // 服务需要支付的赠金
            'zc_fuwu_d'     => '0.00', // 服务需要支付的店转
            'zc_allfuwu_z'  => '0.00',
            'yhj_list'      => [],
        ];

        //获取订单总金额
        $order_amout       = isset($param['order_amout']) ? $param['order_amout'] : 0;         // 订单总计
        $customer_id       = isset($param['customer_id']) ? intval($param['customer_id']) : 0; // 客户id
        $yhj_amount        = isset($param['yhj_amount']) ? abs($param['yhj_amount']) : 0;      // 优惠劵金额
        $order_goods       = isset($param['goods']) ? $param['goods'] : []; // 订单商品

        $coupon_id       = isset($param['coupon_id']) ? $param['coupon_id'] : 0; // 优惠券id
//        $order_type        = isset($param['order_type']) ? abs($param['order_type']) : 0;// 订单的业务类型
        $business_type     = isset($param['business_type']) ? abs($param['business_type']) : 0;// 订单的业务类型


        if ($order_amout < 0) {
            // 如果订单金额为0，则直接返回数据
            return resultArray(['error'=>'订单金额异常，无法获取客户支付金额']);
        }
        if(empty($order_goods)){
            return resultArray(['error'=>'无需出库商品']);
        }
        $coupon_use_type = 0;
        if(!empty($coupon_id)){
            $coupon=DB::name('coupon')->where('id',$coupon_id)->where('status',0)->find();
            if(!empty($coupon)){
                $yhj_amount = $coupon['denomination']; //优惠券优惠金额
                $coupon_use_type = $coupon['use_type'];  //1 商品可用 2服务可用
            }else{
                return resultArray(['error'=>'优惠券不存在']);
            }
        }



        // 按照当前逻辑，订单仅是服务或者疤痕，所以下述处理按照一种客户的余额进行处理
        $balanceList = Db::name('customer_balance')
            ->where([['customer_id','=',$customer_id]])
            ->column('money,complimentary_money,shop_transfer_money','balance_category_id');
        if(empty($balanceList)){
            return resultArray(['error'=>'客户余额数据异常']);
        }

        $money = $complimentary_money = $shop_transfer_money = 0;
        foreach($balanceList as $k=>$v){
            $money = bcadd($money,$v['money'],2);
            $complimentary_money = bcadd($complimentary_money,$v['complimentary_money'],2);
            $shop_transfer_money = bcadd($shop_transfer_money,$v['shop_transfer_money'],2);
        }
        $customerMoney = bcadd(bcadd($money,$complimentary_money,2),$shop_transfer_money,2);
        if($customerMoney<0){
            return resultArray(['error'=>'客户余额为负,无法下单']);
        }




        $prestock_goods_ids = [];
        $customerModel = new CustomerModel();
        $kcbj = $kczj =  $kcdz = [];
        $yhq_yh_bj = $yhq_yh_zj = $yhq_yh_dz = [];
        $cjyh_yh_bj = $cjyh_yh_zj = $cjyh_yh_dz = [];
        $product_arr = $project_arr = [];
        $productAmount = [];
        $projectAmount = [];
        $is_have_cjyh = [];
        $is_have_goods = [];
        $is_have_service = [];
        $cjyh = 0;

        foreach($order_goods as $k=>$val){
            if($val['prestock_type'] != 3){
                if(!in_array($val['business_type'],[1,2,3,4])){
                    return resultArray(['error'=>$val['category_name']."-请选择项目分类"]);
                }
                if($val['business_type'] == 2 && !in_array($val['business_two_type'],[1,2])){
                    return resultArray(['error'=>$val['category_name']."-请选择项目二级分类"]);
                }
                if($val['prestock_type'] == 2){
                    array_push($prestock_goods_ids,$val['id']);
                    //存货
                    if($val['number'] < $val['out_num']){
                        return resultArray(['error'=>$val['category_name']."-存货数量超过出库数量"]);
                    }
                }
                if($val['is_project'] == 1 && $val['prestock_type'] != 3){
                    array_push($is_have_goods,1);
                    $productAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                    array_push($product_arr,$val);
                }else{
                    if($val['id'] != 170){
                        $projectAmount[] = bcmul($val['pay_price'], $val['number'], 2);
                    }
                    array_push($is_have_service,1);
                    array_push($project_arr,$val);
                }

                if($val['id'] == 170 ){
                    $cjyh = bcmul($val['pay_price'], $val['number'], 2);
                    array_push($is_have_cjyh,1);
                }
            }
        }

        if($coupon_use_type == 1 && empty($is_have_goods)){
            return resultArray(['error'=>'优惠券-无可使用的商品']);
        }

        if($coupon_use_type == 2 && empty($is_have_service)){
            return resultArray(['error'=>'优惠券-无可使用的服务']);
        }

        //排查如果有预存货不能添加
        $may_prestock_ids = DB::name('shop_goods')->where('is_prestock',1)->column('id'); //可以预存货的id
        //针对预存货商品，进行判定
        if(!empty($prestock_goods_ids)){
            $prestock_diff = array_diff($prestock_goods_ids,$may_prestock_ids);
            if(!empty($prestock_diff)){
                return resultArray(['error'=>'有异常预存货商品']);
            }
        }

        $is_have_cjyh_count = count($is_have_cjyh);
        if($is_have_cjyh_count >1){
            return resultArray(['error'=>"同一个单子不能出现两项冲减优惠"]);
        }

        if($is_have_cjyh_count >0 && empty($is_have_goods)){
            return resultArray(['error'=>"冲减优惠没有优惠商品"]);
        }




        $productAmount = bcadd(0,array_sum($productAmount),2); //商品之和
        $projectAmount = bcadd(0,array_sum($projectAmount),2); //项目之和

        if($yhj_amount > $productAmount && $coupon_use_type == 1 ){
            return resultArray(['error'=>"优惠券金额超过商品总金额，无法使用"]);
        }

        if($yhj_amount > $projectAmount && $coupon_use_type == 2 ){
            return resultArray(['error'=>"优惠券金额超过项目总金额，无法使用"]);
        }

        // 获取实际支付的订单金额数据和对应客户需要支付的金额数据
        $actual_order_amout  = bcsub($order_amout,$yhj_amount,2); // 获取订单的实际需要支付金额
        if ($actual_order_amout <= 0) {
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }

        if ($order_amout == 0) {
            // 如果订单金额为0，则直接返回数据
            return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        }

        $product_arr_count = count($product_arr);
        $project_arr_count = count($project_arr);
        $yhq_amount  = $yhj_amount;

        $orderModel = new Order();

        $product_yh_amount =  $product_one_amount = [];
        foreach($product_arr as $pk=>&$pv){

            if($pv['pay_price']>0 && $pv['prestock_type'] != 3){

                list($benj,$zengj,$dianz) = $orderModel->getCustomerBalance($balanceList,$pv['business_type']);
                $customerBalance['money'] = $benj;
                $customerBalance['complimentary_money'] = $zengj;
                $customerBalance['shop_transfer_money'] = $dianz;
                $one_product_amount = bcmul($pv['pay_price'],$pv['number'],2);
                $discount_amount = 0; //优惠金额
                if($productAmount >0 && $cjyh != 0 ){
                    //涉及到冲减优惠
                    if($product_arr_count>1){
                        if($pk+1 == $product_arr_count){
                            $discount_amount = bcsub($cjyh,bcadd(0,array_sum($product_yh_amount),2),2); //最后一个优惠金额
                        }else{
                            $discount_amount = bcmul($cjyh,bcdiv($one_product_amount,$productAmount,2),2); //优惠金额
                        }
                    }else{
                        $discount_amount = bcmul($cjyh,bcdiv($one_product_amount,$productAmount,2),2); //优惠金额
                    }
                    $one_product_amount = bcadd($one_product_amount,$discount_amount,2);
                }else{
                    //未涉及到冲减优惠
                    if($yhj_amount !=0 && $coupon_use_type == 1){

                        $yhj_amount = bcsub(0,$yhj_amount,2);
                        //涉及到优惠券
                        if($product_arr_count>1){
                            if($pk+1 == $product_arr_count){
                                $discount_amount = bcsub($yhj_amount,bcadd(0,array_sum($product_yh_amount),2),2); //最后一个优惠金额
                            }else{
                                $discount_amount = bcmul($yhj_amount,bcdiv($one_product_amount,$productAmount,2),2); //优惠金额
                            }
                        }else{
                            $discount_amount = bcmul($yhj_amount,bcdiv($one_product_amount,$productAmount,2),2); //优惠金额
                        }

                        $customerBalance['actual_order_amout'] = $discount_amount;
                        $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                        $bj = bcadd($pay_money['pay_benjin_amount'],0,2);  //单条优惠后的本金
                        $dz = bcadd($pay_money['pay_dianzhuan_amount'],0,2); //单条优惠后的电转
                        $zj = bcadd($pay_money['pay_zengjin_amount'],0,2); //单条优惠后的赠金
                        array_push($yhq_yh_bj ,$bj);
                        array_push( $yhq_yh_zj ,$zj);
                        array_push($yhq_yh_dz ,$dz);

                        $one_product_amount = bcadd($one_product_amount,$discount_amount,2); //优惠后金额
                    }
                }

                $customerBalance['actual_order_amout'] = $one_product_amount;
                $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                $bj = bcadd($pay_money['pay_benjin_amount'],0,2);  //单条优惠后的本金
                $dz = bcadd($pay_money['pay_dianzhuan_amount'],0,2); //单条优惠后的电转
                $zj = bcadd($pay_money['pay_zengjin_amount'],0,2); //单条优惠后的赠金
                array_push($kcbj ,$bj);
                array_push( $kczj ,$zj);
                array_push($kcdz ,$dz);

                $pv['product_amount'] = $one_product_amount;    //优惠后金额
                array_push($product_yh_amount,$discount_amount);
                array_push($product_one_amount,$one_product_amount);
            }
        }

        $first_product_amount = bcadd(0,array_sum($product_one_amount),2); //第一次优惠后的商品总金额
        //二次计算优惠券的本金赠金和赠金-涉及到商品
        $product_yhqyh_amount = [];
        if($yhj_amount != 0  && $coupon_use_type == 1 && $cjyh != 0 ){
            $kcbj = $kczj =  $kcdz = [];
            foreach($product_arr as $pkk=>&$pvv){
                if($pvv['pay_price']>0 && $pvv['prestock_type'] != 3){
                    list($benj,$zengj,$dianz) = $orderModel->getCustomerBalance($balanceList,$pvv['business_type']);
                    $customerBalance['money'] = $benj;
                    $customerBalance['complimentary_money'] = $zengj;
                    $customerBalance['shop_transfer_money'] = $dianz;
                    $two_product_amount = $pvv['product_amount'];
                    $discount_amount = 0; //优惠金额
                    if($first_product_amount >0){
                        if($product_arr_count>1){
                            if($pkk+1 == $product_arr_count){
                                $discount_amount = bcsub($yhq_amount,bcadd(0,array_sum($product_yhqyh_amount),2),2); //最后一个优惠金额
                            }else{
                                $discount_amount = bcmul($yhq_amount,bcdiv($two_product_amount,$first_product_amount,2),2); //优惠金额
                            }
                        }else{
                            $discount_amount = bcmul($yhq_amount,bcdiv($two_product_amount,$first_product_amount,2),2); //优惠金额
                        }

                        $customerBalance['actual_order_amout'] = $discount_amount;
                        $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                        $bj = bcadd($pay_money['pay_benjin_amount'],0,2);  //单条优惠后的本金
                        $dz = bcadd($pay_money['pay_dianzhuan_amount'],0,2); //单条优惠后的电转
                        $zj = bcadd($pay_money['pay_zengjin_amount'],0,2); //单条优惠后的赠金
                        array_push($yhq_yh_bj ,$bj);
                        array_push( $yhq_yh_zj ,$zj);
                        array_push($yhq_yh_dz ,$dz);

                        $two_product_amount = bcsub($two_product_amount,$discount_amount,2); //优惠后金额
                    }

                    array_push($product_yhqyh_amount,$discount_amount);

                    $customerBalance['actual_order_amout'] = $two_product_amount;
                    $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                    $bj = bcadd($pay_money['pay_benjin_amount'],0,2);  //单条优惠的本金
                    $dz = bcadd($pay_money['pay_dianzhuan_amount'],0,2); //单条优惠的电转
                    $zj = bcadd($pay_money['pay_zengjin_amount'],0,2); //单条优惠的赠金
                    array_push($kcbj ,$bj);
                    array_push( $kczj ,$zj);
                    array_push($kcdz ,$dz);
                }
            }
        }


        //项目
        $project_yh_amount = [];
        foreach ($project_arr as $jk => $jv) {
            $bj = $zj = $dz = 0.00;

            if( $jv['prestock_type'] != 3){
                if($jv['id'] != 170 && $jv['pay_price']>0){
                    list($benj,$zengj,$dianz) = $orderModel->getCustomerBalance($balanceList,$jv['business_type']);
                    $customerBalance['money'] = $benj;
                    $customerBalance['complimentary_money'] = $zengj;
                    $customerBalance['shop_transfer_money'] = $dianz;
                    $one_project_amount = bcmul($jv['pay_price'],$jv['number'],2);
                    $discount_amount = 0;
                    if($yhj_amount !=0 && $coupon_use_type == 2){
                        $yhj_amount = bcsub(0,$yhj_amount,2);
                        //涉及到优惠券
                        if($project_arr_count>1){
                            if($jk+1 == $project_arr_count){
                                $discount_amount = bcsub($yhj_amount,bcadd(0,array_sum($project_yh_amount),2),2); //最后一个优惠金额
                            }else{
                                $discount_amount = bcmul($yhj_amount,bcdiv($one_project_amount,$projectAmount,2),2); //优惠金额
                            }
                        }else{
                            $discount_amount = bcmul($yhj_amount,bcdiv($one_project_amount,$projectAmount,2),2); //优惠金额
                        }
                        $one_project_amount = bcadd($one_project_amount,$discount_amount,2); //优惠后金额
                        $customerBalance['actual_order_amout'] = $discount_amount;
                        $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                        $bj = bcadd($pay_money['pay_benjin_amount'],0,2);  //单条优惠后的本金
                        $dz = bcadd($pay_money['pay_dianzhuan_amount'],0,2); //单条优惠后的电转
                        $zj = bcadd($pay_money['pay_zengjin_amount'],0,2); //单条优惠后的赠金
                        array_push($yhq_yh_bj ,$bj);
                        array_push( $yhq_yh_zj ,$zj);
                        array_push($yhq_yh_dz ,$dz);
                        array_push($project_yh_amount,$discount_amount);
                    }
                    $customerBalance['actual_order_amout'] = $one_project_amount;
                    $pay_money = $customerModel->getCustomerAmountConsumed($customerBalance); //获取订单消耗的本金、赠金、店转
                    $bj = bcadd($pay_money['pay_benjin_amount'],0,2);
                    $dz = bcadd($pay_money['pay_dianzhuan_amount'],0,2);
                    $zj = bcadd($pay_money['pay_zengjin_amount'],0,2);
                    array_push($kcbj ,$bj);
                    array_push( $kczj ,$zj);
                    array_push($kcdz ,$dz);
                }
            }
        }

//        var_dump($kcbj,$kczj,$kcdz);die;




        //
        // 本 增
        // 1 2
        // 1 1=0 2=0 -此种情况直接扣除本金即可，可将本金扣为负数
        // 2 1=0 2>0 -此种情况先判断赠金是否够用，若够用则结束，若不够需要将本金扣为负数
        // 3 1=0 2<0 --
        // 4 1>0 2=0 -此种情况直接扣除本金即可，可将本金扣为负数
        // 5 1>0 2>0 -此种情况按照本金/赠金的比例扣除本金和赠金，赠金最多全部抵扣，不可扣为负数，依旧不足时可将本金扣为负数
        // 6 1>0 2<0 --
        // 7 1<0 2=0 -此种情况直接扣除本金即可，可将本金扣为负数
        // 8 1<0 2>0 -此种情况先判断赠金是否够用，若够用则结束，若不够需要将本金扣为负数
        // 9 1<0 2<0 --
        //
//         if ($complimentary_money == 0) { // 1,4,7 仅扣本
//            $retuenData[$balanceType[$business_type]['this'].'_y'] = $actual_order_amout;
//         } else if ($money <= 0 && $complimentary_money > 0) { // 2,7 新赠后本
//            if ($complimentary_money >= $actual_order_amout) {
//                $retuenData[$balanceType[$business_type]['this'].'_z'] = $actual_order_amout;
//            } else {
//                $retuenData[$balanceType[$business_type]['this'].'_z'] = $complimentary_money;
//                $retuenData[$balanceType[$business_type]['this'].'_y'] = bcsub($actual_order_amout,$complimentary_money,2);
//            }
//         } else if ($money > 0 && $complimentary_money > 0) { // 5 先比例在余额
//            // $bili       = bcdiv($complimentary_money,bcadd($money,$complimentary_money),10); // 获取折扣比例
//            // $bili_complimentary_money = bcmul($actual_order_amout,$bili,2); // 获取比例赠金，实际支付本金为避免误差用减法计算(实际支付-实际支付赠金)
//            $bilizengAdd = bcadd($money,$complimentary_money,2);
//            $bilizengCheng = bcmul($actual_order_amout,$complimentary_money,4); //
//            $bili_complimentary_money = bcdiv($bilizengCheng,$bilizengAdd,2);
//            if ($complimentary_money >= $bili_complimentary_money) { // 如果剩余赠金>=比例赠金
//                $pay_complimentary_money = $bili_complimentary_money; // 实际支付赠金为比例赠金
//            } else {
//                $pay_complimentary_money = $complimentary_money; // 实际支付赠金为剩余赠金
//            }
//            $retuenData[$balanceType[$business_type]['this'].'_z'] = $pay_complimentary_money;
//            $retuenData[$balanceType[$business_type]['this'].'_y'] = bcsub($actual_order_amout,$pay_complimentary_money,2);
//         }else{
//             return resultArray(['error'=>'客户金额异常']);
//         }

        $business_type = 2;
        $retuenData[$balanceType[$business_type]['this'].'_y'] = bcadd(array_sum($kcbj),0,2); //实际支付本金
        $retuenData[$balanceType[$business_type]['this'].'_d'] = bcadd(array_sum($kcdz),0,2); //实际支付店转
        $retuenData[$balanceType[$business_type]['this'].'_z'] = bcadd(array_sum($kczj),0,2);  //实际支付

        // 设置支付总金额
        $retuenData[$balanceType[$business_type]['all'].'_z']  = $actual_order_amout;

        $yhjlist     = Db::name('coupon_provide_customer')->where([['customer_id','=',$customer_id],['staus','=',0]])->select()->toArray();

        $yhjzbIds    = array_unique(array_column($yhjlist,'coupon_id'));
        //$yhjZbList   = Db::name('coupon')->where([['use_type','=',$business_type],['id','in',$yhjzbIds]])->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');
        $yhjZbList   = Db::name('coupon')->where([['id','in',$yhjzbIds]])->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');

        $allList = [];
        foreach ($yhjlist as $key => $val){
            if (isset($yhjZbList[$val['coupon_id']])) {
                //时间满足
                if ($yhjZbList[$val['coupon_id']]['start_time'] <= time() && time() <= $yhjZbList[$val['coupon_id']]['end_time']) {
                    //金额满足
                    if ($yhjZbList[$val['coupon_id']]['use_threshold'] == 0 || $order_amout >= $yhjZbList[$val['coupon_id']]['use_threshold']){
                        $yhjlist[$key]['use_type']      = $yhjZbList[$val['coupon_id']]['use_type'];
                        $yhjlist[$key]['type']          = $yhjZbList[$val['coupon_id']]['type'];
                        $yhjlist[$key]['denomination']  = $yhjZbList[$val['coupon_id']]['denomination'];
                        $yhjlist[$key]['name']          = $yhjZbList[$val['coupon_id']]['name'];
                        $yhjlist[$key]['start_time']    = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['start_time']);
                        $yhjlist[$key]['end_time']      = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['end_time']);
                        array_push($allList,$yhjlist[$key]);
                    }
                }
            }
        }

        $retuenData['yhj_list']  = $allList;
        //  print_r($balanceList);exit;
        return resultArray(['data' => $retuenData,'error'=>'获取成功']);
        //----

        //获取用户的余额
        $customerBalance = Db::name('customer_balance')->where([['customer_id','=',$customer_id]])->select()->toArray();
        $cusetomer_goods_order_amout = [];
        $cusetomer_fuwu_order_amout  = [];
        foreach ($customerBalance as $key => $val){
            if ($val['balance_category_id'] == 1){
                $cusetomer_order_amout['money']                 = $val['money'];
                $cusetomer_order_amout['complimentary_money']   = $val['complimentary_money'];
                $cusetomer_order_amout['shop_transfer_money']   = $val['shop_transfer_money'];
                $cusetomer_order_amout['bili']                  = empty($val) ?[] :explode('/', $val['proportion']) ;
            }else if($val['balance_category_id'] == 2){
                $cusetomer_fuwu_order_amout['money']                 = $val['money'];
                $cusetomer_fuwu_order_amout['complimentary_money']   = $val['complimentary_money'];
                $cusetomer_fuwu_order_amout['shop_transfer_money']    = $val['shop_transfer_money'];
                $cusetomer_fuwu_order_amout['bili']                  = empty($val) ?[] :explode('/', $val['proportion']) ;
            }
        }
        $is_order = 1;
        $is_goods = 1;
        $goods_order_amout = bcsub($goods_order_amout,$yhj_amount,2);
        if ($goods_order_amout > 0) {
            if (empty($cusetomer_order_amout)) {
                $is_order = 0;
            }else if ($cusetomer_order_amout['money'] == 0) {
                $is_order = 0;
            }else if ($cusetomer_order_amout['money'] > 0){
                if (empty($cusetomer_order_amout['bili']) || (isset($cusetomer_order_amout['bili'][0]) && empty($cusetomer_order_amout['bili'][0]))){
                    $blall  = 1;//总
                    $bly    = 1;//原
                    $blz    = 0;
                }else{
                    $blall  = $cusetomer_order_amout['bili'][0] + $cusetomer_order_amout['bili'][1];//总
                    $bly    = $cusetomer_order_amout['bili'][0];//原
                    $blz    = $cusetomer_order_amout['bili'][1];//曾
                }
                $zc_goods_y   = bcmul(bcdiv($bly,$blall,2),$goods_order_amout,2);//zc支付原
                $zc_goods_z   = bcsub($goods_order_amout,$zc_goods_y,2);//支付曾

                if ($zc_goods_y > $cusetomer_order_amout['money']) {
                    $is_order = 0;
                } else {
                    if ($zc_goods_z > $cusetomer_order_amout['complimentary_money']) {
                        $zc_z_chae      = bcsub($zc_goods_y,$cusetomer_order_amout['complimentary_money'],2);
                        $zc_y_jiachae   = bcadd($cusetomer_order_amout['money'],$zc_z_chae,2);
                        if ($zc_y_jiachae >= $cusetomer_order_amout['money']) {
                            $is_order = 0;
                        }else{
                            $zc_goods_y = $zc_y_jiachae;
                            $zc_goods_z = $zc_z_chae;
                        }
                    }
                    // print_r($is_order);exit;
                }
            }
        }else{
            $goods_order_amout = '0';
        }
        $fuwu_order_amout = bcsub($fuwu_order_amout,$yhj_amount,2);
        if ($fuwu_order_amout > 0) {
            if (empty($cusetomer_fuwu_order_amout) || !isset($cusetomer_fuwu_order_amout['money'])) {
                $is_goods = 0;
            }else if ($cusetomer_fuwu_order_amout['money'] == 0) {
                $is_goods = 0;
            }else if ($cusetomer_fuwu_order_amout['money'] > 0){
                if (empty($cusetomer_order_amout['bili']) || (isset($cusetomer_order_amout['bili'][0]) && empty($cusetomer_order_amout['bili'][0]))){
                    $blall  = 1;//总
                    $bly    = 1;//原
                    $blz    = 0;
                }else{
                    $blall  = $cusetomer_fuwu_order_amout['bili'][0] + $cusetomer_fuwu_order_amout['bili'][1];//总
                    $bly    = $cusetomer_fuwu_order_amout['bili'][0];//原
                    $blz    = $cusetomer_fuwu_order_amout['bili'][1];//曾
                }
                $zc_fuwu_y   = bcmul(bcdiv($bly,$blall,2),$fuwu_order_amout,2);//zc支付原
                $zc_fuwu_z   = bcsub($fuwu_order_amout,$zc_fuwu_y,2);//支付曾
                if ($zc_fuwu_y > $cusetomer_fuwu_order_amout['money']) {
                    $is_goods = 0;
                } else {
                    if ($zc_fuwu_z >= $cusetomer_fuwu_order_amout['complimentary_money']) {
                        $zc_z_chae      = bcsub($zc_fuwu_z,$cusetomer_fuwu_order_amout['complimentary_money'],2);
                        $zc_y_jiachae   = bcadd($cusetomer_fuwu_order_amout['money'],$zc_z_chae,2);
                        if ($zc_y_jiachae > $cusetomer_fuwu_order_amout['money']) {
                            $is_goods = 0;
                        }else{
                            $zc_fuwu_y = $zc_y_jiachae;
                            $zc_fuwu_z = $zc_z_chae;
                        }
                    }
                }
            }
        }else{
            $fuwu_order_amout = '0';
        }
        if ($is_order == 0 || $is_goods ==0) {
            return resultArray(['error' => '客户余额不足']);
        }
        $data                  = [];
        $data['zc_goods_y']    = $zc_goods_y ?? "0";
        $data['zc_goods_z']    = $zc_goods_z ?? "0";
        $data['zc_allgoods_z'] = $goods_order_amout.'';
        $data['zc_fuwu_y']     = $zc_fuwu_y ?? "0";
        $data['zc_fuwu_z']     = $zc_fuwu_z ?? "0";
        $data['zc_allfuwu_z']  = $fuwu_order_amout.'';

        $yhj_type    = $goods_order_amout > 0 ? 1 : 2 ;
        $order_amout = $goods_order_amout>0 ? $goods_order_amout : $fuwu_order_amout;

        $yhjlist     = Db::name('coupon_provide_customer')->where([['customer_id','=',$customer_id],['staus','=',0]])->select()->toArray();

        $yhjzbIds    = array_unique(array_column($yhjlist,'coupon_id'));
        $yhjZbList   = Db::name('coupon')->where([['use_type','=',$yhj_type],['id','in',$yhjzbIds]])->column(['use_type','type','denomination','use_threshold','name','start_time','end_time'],'id');

        $allList = [];
        foreach ($yhjlist as $key => $val){
            if (isset($yhjZbList[$val['coupon_id']])) {
                //时间满足
                if ($yhjZbList[$val['coupon_id']]['start_time'] <= time() && time() <= $yhjZbList[$val['coupon_id']]['end_time']) {

                    // print_r($yhjZbList[$val['coupon_id']]['use_threshold']);
                    // print_r('---'.$key);
                    // print_r('---'.$order_amout);
                    //金额满足
                    if ($yhjZbList[$val['coupon_id']]['use_threshold'] == 0 || $order_amout >= $yhjZbList[$val['coupon_id']]['use_threshold']){
                        $yhjlist[$key]['use_type']      = $yhjZbList[$val['coupon_id']]['use_type'];
                        $yhjlist[$key]['type']          = $yhjZbList[$val['coupon_id']]['type'];
                        $yhjlist[$key]['denomination']  = $yhjZbList[$val['coupon_id']]['denomination'];
                        $yhjlist[$key]['name']          = $yhjZbList[$val['coupon_id']]['name'];
                        $yhjlist[$key]['start_time']    = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['start_time']);
                        $yhjlist[$key]['end_time']      = date('Y-m-d H:i:s',$yhjZbList[$val['coupon_id']]['end_time']);
                        array_push($allList,$yhjlist[$key]);
                    }
                }
            }
        }

        $data['yhj_list']  = $allList;
        return resultArray(['data' => $data]);
    }
    /**
     * 服务列表
     * @param  Service $serviceModel
     * @return Json
     */
    public function readServiceList(Service $serviceModel): Json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $serviceModel->readServiceList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 服务列表导出
     * @param  Service $serviceModel
     * @return Json
     */
    public function readServiceList_export(Service $serviceModel): Json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export'] = 1;
        $data = $serviceModel->readServiceList($this->param);
        if (!$data) {
            return resultArray(['error' => $serviceModel->getError()]);
        }
        $callName = ['create_time' => '服务日期','customer_name' =>'客户姓名','sex_name' =>'性别','age' => '年龄','shop_name' => '门店','market_name' => '市场','shop_name' => '服务人员','service_type_name' => '服务类型','sy_num' => '服务次数'];
        // print_r($callName);exit;
        $downUrl = exportExcelData('service',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新增客服回访
     */
    public function returnVistList(ReturnVist $ReturnVist): json
    {
        $shopIds = $this->getCommonShopIdsCollectByUserType();
        $this->param['shopIds'] = $shopIds;
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data]);
    }

    /**
     * 新增客服回访
     */
    public function returnVistList_export(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $this->param['export']  = 1;
        $data = $ReturnVist->getDataList($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        $callName = [
            'customer_name' => '客户名称',
            'telephone' =>'门店名称',
            'type' =>'回访类型',
            'return_visitor_name' =>'员工名称',
            'return_visit_time' => '客访时间',
            'return_visit_content' => '客访内容',
            'create_time' => '创建时间'
        ];
        // print_r($callName);exit;
        $downUrl = exportExcelData('list',$callName,$data['list'],'xlsx',1);
        return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);
    }

    /**
     * 新增客服回访
     */
    public function addVistList(ReturnVist $ReturnVist): json
    {
        $this->param['user_id'] = $this->userInfo['id'];
        $data = $ReturnVist->addData($this->param);
        if (!$data) {
            return resultArray(['error' => $ReturnVist->getError()]);
        }
        return resultArray(['data' => $data,'error'=>'创建成功']);
    }









}
